package org.act.xservices.rt.xcontainer.transport.http.codec;

import org.apache.asyncweb.common.HttpRequest;
import org.apache.asyncweb.server.HttpServiceContext;
import org.apache.asyncweb.server.ServiceContainer;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.DefaultWriteRequest;
import org.apache.mina.core.write.WriteRequest;

/**
 * Convert HttpRequest to ATFHttpServiceContext, and find the HttpSession of this Request, 
 * bind to the ATFHttpServiceContext.
 * 
 * @LastModifyTime 2008-12-23
 * @CreationTime
 * @author Lizq [lizq@act.buaa.edu.cn]
 * @since JDK1.5
 */
public class ContextConverterFilter extends IoFilterAdapter {

	private ServiceContainer container;

	public ContextConverterFilter(ServiceContainer container){
		this.container = container;
	}
	
	@Override
	public void filterWrite(NextFilter nextFilter, IoSession session,
			WriteRequest writeRequest) throws Exception {
		
		nextFilter.filterWrite(session, new DefaultWriteRequest(
				((HttpServiceContext) writeRequest.getMessage())
						.getCommittedResponse(), writeRequest.getFuture()));
	}

	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session,
			Object message) throws Exception {
		
		nextFilter.messageReceived(session, 
				new ATFHttpServiceContext(session, (HttpRequest) message, container));
	}
	
}
